﻿@using IotClientApp.Shared;
@using IotClientApp.Shared.Enums;
@using Newtonsoft.Json;
<h3>DeviceConfigSave_Dialog</h3>
@inject ISnackbar Snackbar
@inject HttpClient httpClient
<MudDialog>
    <TitleContent>
        <MudText Typo="Typo.h6">
            <MudIcon Icon="@Icons.Material.Filled.DeleteForever" Class="mr-3 mb-n1" />
            @Title
        </MudText>
    </TitleContent>
    <DialogContent>
        <MudHidden Value="@DeviceConfigInfo.Id"></MudHidden>
        <MudTextField @bind-Value="DeviceConfigInfo.Name" Label="名称" />
        <MudTextField @bind-Value="DeviceConfigInfo.Value" Label="值" />
        <MudTextField @bind-Value="DeviceConfigInfo.EnumInfo" Label="备注" />
        <MudTextField Value="@DeviceConfigInfo.Desc" Label="描述" />
    </DialogContent>
    <DialogActions>
        <MudButton OnClick="Cancel">取消</MudButton>
        <MudButton Color="Color.Success" OnClick="EditConfigItem">保存</MudButton>
    </DialogActions>
</MudDialog>
@code {
    [CascadingParameter] MudDialogInstance MudDialog { get; set; }
    [Parameter]
    public DeviceConfigInfoModel DeviceConfigInfo { get; set; }
    [Parameter]
    public string Title { get; set; } = "新增";
    private void Cancel()
    {
        MudDialog.Cancel();
    }
    private async void EditConfigItem()
    {
        var response = await httpClient.PostAsJsonAsync("api/DeviceConfig/SaveDeviceConfigInfo", DeviceConfigInfo);
        try
        {
            if (response.IsSuccessStatusCode)
            {
                var responseContent = await response.Content.ReadAsStringAsync();
                var result = JsonConvert.DeserializeObject<ApiResult<string>>(responseContent);

                if (result != null && result.Code == ResultCode.Success)
                {
                    Snackbar.Add(Title, Severity.Success);
                    MudDialog.Close(DialogResult.Ok(DeviceConfigInfo.Id));
                }
                else if (result != null && result.Code != ResultCode.Success)
                {
                    Snackbar.Add(result.ErrorMsg, Severity.Error);
                }
            }
        }
        catch (Exception ex)
        {
            Snackbar.Add(ex.Message, Severity.Error);
            Console.WriteLine(ex.Message);
        }
    }
}